//
//  ViewController.m
//  BluetoothTest
//
//  Created by Chen Ming on 2017/11/23.
//  Copyright © 2017year Bioland. All rights reserved.
//

/**
 Bluetooth needs real machine test
 */

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "CMBleTools.h"

#define infoPackageLenth    15
#define processLenth    8
#define resultLenth     14


@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate,
UITableViewDelegate,UITableViewDataSource>
{
    CBCentralManager *centerManager;
    NSMutableArray *peripheralsArray;
    NSMutableArray *Services;
    NSString *tempStr;
    CBPeripheral *_currentPeripheral;
    NSInteger _selecetedIndex;
    NSString *_glycemicValue;
    
    NSInteger _maxPackageLength;
    BOOL isBloodPress30;
    
    NSMutableArray *otherArr;
    NSMutableArray *tempArr;
    prePacketStyle _Style;
    BOOL isBloodSP;
    BOOL isFirstResult;
 
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"blood sugar/blood pressure Demo";
    // Do any additional setup after loading the view, typically from a nib.
    Services = [NSMutableArray array];
    peripheralsArray = [NSMutableArray array];
    self.BTableView.delegate = self;
    self.BTableView.dataSource = self;
    self.BTableView.backgroundColor = [UIColor whiteColor];
    centerManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
}
#pragma mark - reconnect
- (IBAction)ReScanPericral:(UIButton *)sender{
    /*if (_currentPeripheral) {
    [centerManager connectPeripheral:_currentPeripheral options:nil];
    }else{
        self.showLabel.text = @"Please connect the device first";
    }*/

    if (_currentPeripheral) {
        [self disconnectPeripheral:centerManager peripheral:_currentPeripheral];
    }
    [peripheralsArray removeAllObjects];
    [self.BTableView reloadData];
    _showLabel.text = nil;
    [centerManager scanForPeripheralsWithServices:nil options:nil];
}
#pragma mark   Central proxy method implementation
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@"Not recognized");
            break;
        
        case CBCentralManagerStateResetting:
            NSLog(@"Restart");
            break;
            
        case CBCentralManagerStatePoweredOff:
            NSLog(@"closed");
            break;
            
        case CBCentralManagerStateUnsupported:
            NSLog(@"not support");
            break;
            
        case CBCentralManagerStatePoweredOn:
            NSLog(@"Opened up");
            /** Start scanning peripheral devices*/
            [centerManager scanForPeripheralsWithServices:nil options:nil];
            break;
            
        case CBCentralManagerStateUnauthorized:
            NSLog(@"No authorization");
            break;
            
        default:
            break;
    }
}

#pragma mark - After scanning to the peripheral, it will enter the method.
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI
{
    NSLog(@"Scan to:%@",peripheral.name);
    if (peripheral.name.length > 1) {
        NSLog(@"Scan to:%@",peripheral.name);
        NSInteger index;
        if ([peripheral.name containsString:@"BGM"]) {
            index = 1;
            
            _currentPeripheral = peripheral;
            isBloodSP = YES;
            [centerManager connectPeripheral:peripheral options:nil];
            
        }else if ([peripheral.name containsString:@"BPM"]) {
            index = 2;
        }else {
            index = 0;
        }
        [self insertTableView:peripheral WithConModel:index];
    }
}
//insert table data
-(void)insertTableView:(CBPeripheral *)peripheral WithConModel:(NSInteger)index{
    NSArray *tempArr = [peripheralsArray valueForKey:peripheralItem];
    if(![tempArr containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tempArr.count inSection:0];
        [indexPaths addObject:indexPath];
        
        NSDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:peripheral forKey:peripheralItem];
        [dic setValue:@(index) forKey:@"BloodSP"];
        [peripheralsArray addObject:dic];
        [self.BTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
#pragma mark - Connecting peripherals will enter the following method        whether succeed
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>Connect to device named （%@） - successful",peripheral.name);
    //set peripheral of CBPeripheralDelegate
    NSLog(@"Stop scanning peripheral devices");
    [centerManager stopScan];
    _showLabel.text = @"Device is connected";
    [peripheral setDelegate:self];
    /** Start scanning for services that connect peripherals*/
    [peripheral discoverServices:nil];
}
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>Peripheral connection disconnected  %@: %@\n", [peripheral name], [error localizedDescription]);
    _showLabel.text = @"Device is disconnected";
    /** Automatic disconnection after sending data */
    /*if (peripheralsArray.count > _selecetedIndex) {
        [peripheralsArray removeObjectAtIndex:_selecetedIndex];
    }
    [self.BTableView reloadData];*/
    
    if (_currentPeripheral) {
        [self disconnectPeripheral:centerManager peripheral:_currentPeripheral];
    }
    [peripheralsArray removeAllObjects];
    [self.BTableView reloadData];
    _showLabel.text = nil;
    [centerManager scanForPeripheralsWithServices:nil options:nil];
    
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>Connect to the name of（%@）Device - failure,reason:%@",[peripheral name],[error localizedDescription]);
}
#pragma mark - Scanning peripheral service
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@">>>Scan to service：%@",peripheral.services);
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services) {
        [Services addObject:service];
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
#pragma mark - Stop scanning and disconnect
-(void)disconnectPeripheral:(CBCentralManager *)centralManager
                 peripheral:(CBPeripheral *)peripheral{
    //Stop scanning
    [centralManager stopScan];
    //Disconnect
    [centralManager cancelPeripheralConnection:peripheral];
}
#pragma mark - Write specific values
-(void)WriteDataToCharacteristic:(NSInteger)GetData
{
    //_showLabel.text = nil;
    /** 0  send infomation packet ，1   send data packet */
    NSData *sendData = nil;
    if (GetData == 0) {
        sendData = [CMBleTools SendDataWithCurrentDate:InformationPacketStyle];
    }else if (GetData == 1){
        sendData = [CMBleTools SendDataWithCurrentDate:DataPacketStyle];
    }else if (GetData == 2){
        /** Blood pressure starter package */
        sendData = [CMBleTools pressureSendDataWithCurrentDate:preStartPacketStyle];
    }
    else if(GetData == 3)
    {
        /** Read History */
        sendData = [CMBleTools pressureSendDataWithCurrentDate:preDataPacketStyle];
    }
    /** Make sure there is a device connection currently */
    if (_currentPeripheral) {
        for (CBService *service in _currentPeripheral.services)
        {
            if ([service.UUID.UUIDString isEqualToString:PERIPHERALSERVER]) {
                for (CBCharacteristic *characteristic in service.characteristics)
                {
                    if ([characteristic.UUID.UUIDString isEqualToString:characteristicUUID1]) {
                        [self writeCharacteristic:_currentPeripheral characteristic:characteristic value:sendData];
                    }
                }
            }
        }
    }else{
        self.showLabel.text = @"Please connect the device first";
    }
}
- (IBAction)sendCommandToGetInformation:(UIButton *)sender{
    isFirstResult=true;
    if (isBloodSP == YES) {
        [self WriteDataToCharacteristic:0];
    }else{
        _Style = preInfoPacketStyle;
        otherArr = [NSMutableArray array];
        tempArr = [NSMutableArray array];
        [self WriteDataToCharacteristic:0];
    }
}

-(IBAction)StartBloodPressure:(UIButton *)sender
{
    
    _Style = preProcessPacketStyle;
    otherArr = [NSMutableArray array];
    tempArr = [NSMutableArray array];
    [self WriteDataToCharacteristic:2];
    
}


- (IBAction)StartBloodPressureHistory:(id)sender {
    
    _Style =preDataPacketStyle;
    otherArr = [NSMutableArray array];
    tempArr = [NSMutableArray array];
    [self WriteDataToCharacteristic:3];
    
}


#pragma mark - write data
-(void)writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value{
    //only characteristic.properties    has write Permissions can be written
    if(characteristic.properties & CBCharacteristicPropertyWrite){
        /*
         Preferably a type parameter can be CBCharacteristicWriteWithResponse or type:CBCharacteristicWriteWithResponse, the difference is whether there will be feedback
         */
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
    }else{
        NSLog(@"This field is not writable!");
    }
}
#pragma mark - Callback after writing data
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
    if (error) {
        NSLog(@"%s, line = %d, erro = %@",__FUNCTION__,__LINE__,error.description);
    }
}
#pragma mark -Getting peripherals Characteristics,Getting Characteristics of value
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error
{
    if (error)
    {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics){
        {
            [peripheral readValueForCharacteristic:characteristic];
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
    
    [self sendCommandToGetInformation:nil];
}
//Getting characteristic of value
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //print characteristic  of UUID and value
    //!attention，value of type is NSData    In the specific development, the data will be parsed according to the method of peripheral protocol.

    /** The returned result is in the 1002 eigenvalue */
 
    
    if ([characteristic.UUID.UUIDString hasPrefix:characteristicUUID2]) {
         NSLog(@"获取到的characteristic uuid:%@ value:%@",characteristic.UUID.UUIDString,[CMBleTools serializeNSDataDisplay:characteristic.value]);
        NSMutableArray *array = [CMBleTools convertDataToHexStr:characteristic.value];
        /** 7-31 */
        if (isBloodSP == YES) {
            /** blood sugar */
            if (array.count > 6) {
                if ([array[2] isEqualToString:HexZero] &&
                    [array[6] isEqualToString:HexTwo]) {
                    /** blood sugar 3.2 protocol     Information package */
                    _showLabel.text = [self dealHexToNSString:characteristic.value AndpacketStyle:InformationPacketStyle];
                }else if ([array[2] isEqualToString:HexThree] &&
                          array.count == 12){
                    /** Blood glucose result packYESage */
                    
                    if(isFirstResult==YES)
                    {
                    
                        _showLabel.text = [self dealHexToNSString:characteristic.value AndpacketStyle:DataPacketStyle];
                        //clear History data                        isFirstResult=NO;
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC));
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            [self WriteDataToCharacteristic:3];
                        });
                    }
                    else//clear History data
                    {
                        isFirstResult=NO;
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC));
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            [self WriteDataToCharacteristic:3];
                        });
                        
                    }
                        
                }
                else if([array[2] isEqualToString:HexZero] &&
                        [array[6] isEqualToString:@"27"])
                {
                    _showLabel.text = [self dealHexToNSString:characteristic.value AndpacketStyle:InformationPacketStyle];
                    
                }
            }
        }else{
            /** blood pressure */
            // NSInteger _maxPackageLength;
            //BOOL isBloodPress30;
            if(array.count>_maxPackageLength)
            {
                _maxPackageLength=array.count;
                if(array.count==18)
                {
                    isBloodPress30=true;
                }
            }
            
            if(isBloodPress30)
            {
                if ([array[2] isEqualToString:@"00"])
                {
                    _showLabel.text=[self DealInfoPackageWithArrV30:array];
                    
                }
                if ([array[2] isEqualToString:@"02"])
                {
                    NSString *proVal = [CMBleTools handStrtoulStr:array[5]];
                    _showLabel.text = proVal;                }
                if ([array[2] isEqualToString:@"03"])
                {
                    _showLabel.text = [self dealPressureDataWithArr:array];
                    
                }
                
                
            }
            else
            {
                array = [self dealBPSubpackageWithArr:array WithStyle:_Style];
                if (array.count >= 8) {
                    if (_Style == preInfoPacketStyle) {
                        
                        _showLabel.text = [self DealInfoPackageWithArr:array];
                        
                        
                    }else if (_Style == preProcessPacketStyle){
                        NSString *proVal = [CMBleTools handStrtoulStr:array[5]];
                        _showLabel.text = proVal;
                    }else if (_Style == preDataPacketStyle){
                        _showLabel.text = [self dealPressureDataWithArr:array];
                    }
                }
                
            }
        }
    }
}
#pragma mark - Processing blood pressure data packet return
-(NSMutableArray *)dealBPSubpackageWithArr:(NSMutableArray *)array
                                 WithStyle:(prePacketStyle)style{
    NSInteger length = 0;
    if (style == preInfoPacketStyle) {
        length = infoPackageLenth;
    }else if (style == preProcessPacketStyle){
        length = processLenth;
    }else if (style == preDataPacketStyle){
        length = resultLenth;
    }
    
    if (tempArr.count == length) {
        [tempArr removeAllObjects];
    }
    
    if (otherArr.count > 0) {
        for (int i = 0; i < otherArr.count; i++) {
            NSString *string = [otherArr objectAtIndex:i];
            [tempArr addObject:string];
        }
        otherArr = [NSMutableArray array];
    }
    
    for (NSInteger i = 0; i < array.count; i++) {
        NSString *string = [array objectAtIndex:i];
        if (tempArr.count < length) {
            [tempArr addObject:string];
        }else{
            [otherArr addObject:string];
        }
    }
    
    if (tempArr.count == length) {
        if ([tempArr[2] isEqualToString:HexThree]){
            _Style = preDataPacketStyle;
            for (int i = 0; i < otherArr.count; i++) {
                NSString *string = [otherArr objectAtIndex:i];
                [tempArr addObject:string];
            }
            [otherArr removeAllObjects];
            if (tempArr.count == resultLenth) {
                return tempArr;
            }
        }else if ([tempArr[2] isEqualToString:HexTwo]){
            return tempArr;
        }else if ([tempArr[2] isEqualToString:HexZero]){
            return tempArr;
        }
    }
    return [NSMutableArray array];
}
#pragma mark - Handling blood pressure results
-(NSString *)dealPressureDataWithArr:(NSArray *)array{
    NSString *timeYear = [CMBleTools handStrtoulStr:array[3]];
    NSString *timeMonth = [CMBleTools handStrtoulStr:array[4]];
    NSString *timeDay = [CMBleTools handStrtoulStr:array[5]];
    NSString *timeHours = [CMBleTools handStrtoulStr:array[6]];
    NSString *timeMinuter = [CMBleTools handStrtoulStr:array[7]];

    NSInteger height;
    if ([array[10] isEqualToString:HexZero]) {
        height = [CMBleTools getDecimalByHex:[NSString stringWithFormat:@"%@",array[9]]];
    }else{
        height = [CMBleTools getDecimalByHex:[NSString stringWithFormat:@"%@%@",array[9],array[10]]];
    }
    NSInteger low = [CMBleTools getDecimalByHex:array[11]];
    NSInteger heat = [CMBleTools getDecimalByHex:array[12]];
    NSString *string = [NSString stringWithFormat:@"%@ year %@ month %@ date %@ hour %@ minute measuring of high pressure %ldmmHg Low pressure %ldmmHg Heartbeat %ld Times/minute",timeYear,timeMonth,
                        timeDay,timeHours,timeMinuter,(long)height,(long)low,(long)heat];
    return string;
}
#pragma mark - Handling blood pressure information package */
-(NSString *)DealInfoPackageWithArr:(NSArray *)array{
    NSString *brandName = [CMBleTools handStrtoulStr:array[4]];
    NSString *typeName = [CMBleTools handStrtoulStr:array[5]];
    NSString *versionName = [CMBleTools handStrtoulStr:array[6]];
    NSString *numberName = [CMBleTools handStrtoulStr:array[7]];
    NSString *string = [NSString stringWithFormat:@"%@%@ %@ %@",
                        [CMBleTools ReturnTureBrandOrInstrument:brandName AndmodelStyle:BrandStyle],[CMBleTools ReturnTureBrandOrInstrument:typeName AndmodelStyle:InstrumentStyle],versionName,numberName];
    return string;
}


-(NSString *)DealInfoPackageWithArrV30:(NSArray *)array{
    NSString *brandName = [CMBleTools handStrtoulStr:array[4]];
    NSString *typeName = [CMBleTools handStrtoulStr:array[6]];
    NSString *numberName = [CMBleTools handStrtoulStr:array[7]];
    NSInteger chargeValue=[CMBleTools getDecimalByHex:array[5]];
    NSString *versionName = [CMBleTools handStrtoulStr:array[6]];
    
    NSString *sn = @"";
    /** deal SN number */
    if (array.count >= 16) {
        NSString *sn1 = [CMBleTools StringToASCII:array[8]];
        NSString *sn2 = [CMBleTools StringToASCII:array[9]];
        NSString *sn3 = [CMBleTools StringToASCII:array[10]];
        NSString *sn4 = [CMBleTools StringToASCII:array[11]];
        NSString *sn5 = [CMBleTools StringToASCII:array[12]];
        NSString *sn6 = [CMBleTools StringToASCII:array[13]];
        NSString *sn7 = [CMBleTools StringToASCII:array[14]];
        NSString *sn8 = [CMBleTools StringToASCII:array[15]];
        NSString *sn9 = [CMBleTools StringToASCII:array[16]];
        sn = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@",sn1,sn2,sn3,sn4,sn5,sn6,sn7,sn8,sn9];
    }
    
    NSString *string = [NSString stringWithFormat:@"%@%@ protocol version：%@ device type：%@ electric value ：%ld%%  serial number：%@",
                        [CMBleTools ReturnTureBrandOrInstrument:brandName AndmodelStyle:BrandStyle],[CMBleTools ReturnTureBrandOrInstrument:typeName AndmodelStyle:InstrumentStyle],versionName,numberName,chargeValue,sn];
    return string;
}



#pragma mark - Handling blood glucose packets and results packages */
-(NSString *)dealHexToNSString:(NSData *)data AndpacketStyle:(PacketStyle)packetStyle
{
    NSMutableArray *array = [CMBleTools convertDataToHexStr:data];
    if (packetStyle == DataPacketStyle) {
        NSString *timeYear = [CMBleTools handStrtoulStr:array[3]];
        NSString *timeMonth = [CMBleTools handStrtoulStr:array[4]];
        NSString *timeDay = [CMBleTools handStrtoulStr:array[5]];
        NSString *timeHours = [CMBleTools handStrtoulStr:array[6]];
        NSString *timeMinuter = [CMBleTools handStrtoulStr:array[7]];
        NSInteger temp1 = [CMBleTools getDecimalByHex:[NSString stringWithFormat:@"%@%@",array[10],array[9]]];;
        float glycemicIndex = (float) temp1 / 18;
        _glycemicValue = [CMBleTools notRounding:glycemicIndex afterPoint:1];
        NSString *string = [NSString stringWithFormat:@"%@ year %@ month %@ date %@ hour %@ minute measuring of Blood glucose value %@ mmol/L",timeYear,timeMonth,
                            timeDay,timeHours,timeMinuter,_glycemicValue];
        return string;
    }else if (packetStyle == InformationPacketStyle){
#pragma mark - The return value in the 2.0 protocol is 15 bits，Need to write the read packet；The 3.0 protocol automatically broadcasts the packet after sending the packet.
        if (array.count == 15) {
            [self WriteDataToCharacteristic:1];
        }
        NSString *brandName = [CMBleTools handStrtoulStr:array[4]];
        NSString *InstrumentName = [CMBleTools handStrtoulStr:array[6]];
        NSString *numberName = [CMBleTools handStrtoulStr:array[7]];
        NSString *sn = @"";
        /** Processing SN number */
        if (array.count >= 16) {
            NSString *sn1 = [CMBleTools StringToASCII:array[8]];
            NSString *sn2 = [CMBleTools StringToASCII:array[9]];
            NSString *sn3 = [CMBleTools StringToASCII:array[10]];
            NSString *sn4 = [CMBleTools StringToASCII:array[11]];
            NSString *sn5 = [CMBleTools StringToASCII:array[12]];
            NSString *sn6 = [CMBleTools StringToASCII:array[13]];
            NSString *sn7 = [CMBleTools StringToASCII:array[14]];
            NSString *sn8 = [CMBleTools StringToASCII:array[15]];
            NSString *sn9 = [CMBleTools StringToASCII:array[16]];
            sn = [NSString stringWithFormat:@"device sn:  %@%@%@%@%@%@%@%@%@",sn1,sn2,sn3,sn4,sn5,sn6,sn7,sn8,sn9];
        }
        /** Refresh the SN number of the device on the Tableview display. */
        NSMutableDictionary *dic = [peripheralsArray objectAtIndex:_selecetedIndex];
        [dic setObject:sn forKey:SNCODE];
        [peripheralsArray replaceObjectAtIndex:_selecetedIndex withObject:dic];
        [self.BTableView reloadData];
        NSString *string = [NSString stringWithFormat:@"%@+%@+%@+%@",
                            [CMBleTools ReturnTureBrandOrInstrument:brandName AndmodelStyle:BrandStyle],[CMBleTools ReturnTureBrandOrInstrument:InstrumentName AndmodelStyle:InstrumentStyle],numberName,sn];
        return string;
    }else
        return nil;
}
#pragma mark - UITableViewDelegate DataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return peripheralsArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSDictionary *dic = [peripheralsArray objectAtIndex:indexPath.row];
    CBPeripheral *per = [dic objectForKey:peripheralItem];
    NSString *string = [dic objectForKey:SNCODE];
    if (string.length > 1) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@+%@",per.name,string];
    }else{
        cell.textLabel.text = per.name;
    }
    NSString *extractedExpr = per.identifier.UUIDString;
    cell.detailTextLabel.text = extractedExpr;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [peripheralsArray objectAtIndex:indexPath.row];
    _selecetedIndex = indexPath.row;
    _currentPeripheral = [dic objectForKey:peripheralItem];
    NSInteger SP = [[dic objectForKey:@"BloodSP"] integerValue];
    if (SP == 2) {
        isBloodSP = NO;
        _Style = preInfoPacketStyle;
    }else{
        isBloodSP = YES;
    }
    [centerManager connectPeripheral:_currentPeripheral options:nil];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yoffSet = scrollView.contentOffset.y;
    if (yoffSet < 0) {
        if (_currentPeripheral) {
            [self disconnectPeripheral:centerManager peripheral:_currentPeripheral];
        }
        [peripheralsArray removeAllObjects];
        [self.BTableView reloadData];
        _showLabel.text = nil;
        [centerManager scanForPeripheralsWithServices:nil options:nil];
    }
}

-(void)dealloc
{
    _currentPeripheral = nil;
     centerManager = nil;
     peripheralsArray = nil;
     Services = nil;
     tempStr = nil;
}

@end
